package com.ssc.chain.tcfp.core.client;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author mingjian
 * @version 1.0
 * Create by 2025/7/10 17:59
 */
public class MemoryUploadStore implements UploadStore {

    private static class UploadData {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        long length;
    }

    private final Map<String, UploadData> store = new ConcurrentHashMap<>();

    @Override
    public void createUpload(String uploadId, long length) {
        UploadData data = new UploadData();
        data.length = length;
        store.put(uploadId, data);
    }

    @Override
    public void append(String uploadId, long offset, InputStream data, long length) throws IOException {
        UploadData uploadData = store.get(uploadId);
        if (uploadData == null) throw new IOException("Upload not found: " + uploadId);
        if (uploadData.baos.size() != offset) throw new IOException("Offset mismatch");

        byte[] buf = new byte[8192];
        long remain = length;
        int read;
        while (remain > 0 && (read = data.read(buf, 0, (int) Math.min(buf.length, remain))) != -1) {
            uploadData.baos.write(buf, 0, read);
            remain -= read;
        }
    }

    @Override
    public long getOffset(String uploadId) {
        UploadData uploadData = store.get(uploadId);
        if (uploadData == null) return 0;
        return uploadData.baos.size();
    }

    @Override
    public void complete(String uploadId) {
        // 无特殊处理
    }

    @Override
    public InputStream getInputStream(String uploadId) throws Exception {
        return null;
    }

    @Override
    public long getUploadLength(String uploadId) {
        UploadData uploadData = store.get(uploadId);
        if (uploadData == null) return -1;
        return uploadData.length;
    }
}
